import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/pages/course/course_question_page.dart';
import 'package:flutter_niandaxue/pages/exampaper/exam_paper_question.dart';
import 'package:flutter_niandaxue/pages/login_page.dart';
import 'package:flutter_niandaxue/service/http_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_niandaxue/config/index.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class HomePage extends StatefulWidget{
  @override
  _HomePageState createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin{
  @override
  bool get wantKeepAlive => true;

  // diff 算法
  GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();
  GlobalKey<RefreshHeaderState> _headerKey = new GlobalKey<RefreshHeaderState>();

  var homePageInfo = null;
  List swiperDataList = [];// 轮播图
  ExamInfo examInfo; // 考试信息
  List courseRows = []; // 最近学习课程
  List examPaperRows = []; // 最近学习试卷
  TabController _tabController ;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: 2);
    _getHomePageData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: KColor.backGroundColor,
      appBar: AppBar(
        title: Text(KString.homeTitle),
      ),
      body: buildBody(context)
    );
  }
  // 空数据显示
  Widget buildBody(context){
    double totalHeight = (courseRows.length >= examPaperRows.length ? courseRows.length:examPaperRows.length)*150.0;
      if(homePageInfo != null){
          return EasyRefresh(
            refreshFooter: ClassicsFooter(
              key: _footerKey,
              bgColor: Colors.white,
              textColor: KColor.refreshTextColor,
              moreInfoColor: KColor.refreshTextColor,
              showMore: true,
              noMoreText: '',
              moreInfo: KString.loading, // 加载中
              loadReadyText: KString.loadReadyText, // 上拉加载
            ),
            refreshHeader: ClassicsHeader(
              key: _headerKey,
              bgColor: Colors.white,
              textColor: KColor.refreshTextColor,
              moreInfoColor: KColor.refreshTextColor,
              showMore: true,
              moreInfo: KString.loading, // 加载中
            ),
            child: ListView(
              children: <Widget>[
                SwiperDiy(
                  swiperDataList:swiperDataList,
                ),
                ExamPromptInformation(
                    examInfo: examInfo
                ),
                Container(
                  margin: EdgeInsets.all(1.0),
                  decoration: new BoxDecoration( // 边框设置
                    color: Colors.white,
                    border: new Border.all(width: 1, color: Colors.white),
                    //设置四周圆角 角度
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                    //设置四周边框
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        color: KColor.primaryColor,
                        alignment: Alignment.centerLeft,
                        height: ScreenUtil().setHeight(80),
                        child: Row(
                          children: <Widget>[
                            Container(
                              child: Icon(Icons.book),
                              margin: EdgeInsets.only(left: 10, right: 10),
                            ),

                            Expanded(
                              child: Text('最近学习',
                                style: KFont.courseTitleStyle,
                              ) ,
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: ScreenUtil().setHeight(totalHeight),
                        color: Colors.white,
                        child: Scaffold(
                          appBar: AppBar(
                            backgroundColor: Colors.white,
                            title: TabBar(
                              indicatorSize: TabBarIndicatorSize.tab,
                              labelColor: Colors.blueAccent,
                              unselectedLabelColor: Colors.black,
                              indicatorColor: Colors.white,
                              tabs: <Widget>[
                                _getTab("课程"),
                                _getTab("试卷"),
                              ],
                              controller: this._tabController,
                            ),
                          ),
                          body: TabBarView(
                            controller: this._tabController,
                            children: <Widget>[
                              new Container(
                                child: HomePageCourseColumn(courseRows:courseRows),
                              ),
                              new Container(
                                child: HomePageExamPaperColumn(examPaperRows: examPaperRows),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                )

              ],

            ),
            onRefresh: () async {
              await _onRefresh();  //下拉刷新
            },
//              loadMore: () async {
////              print('开始加载更多');
////              _getHotGoods();
//              },
          );
      }else{
        return Center(
          child: Text('加载中...'),
        );
      }
  }
  _onRefresh() async{
    HomePage();
  }
  Tab _getTab(titleName){
    return new Tab(
      child: Row(
        children: <Widget>[
          Icon(Icons.book, size: 20,),
          Text(titleName,
            textAlign: TextAlign.left,
            style: TextStyle(
              fontSize: 20,
            ),
          ),
        ],
      ),
    );
  }
  // 获取服务端数据
  void _getHomePageData(){
    homePageInfo = null;
    swiperDataList.clear(); // 轮播图
    examInfo= new ExamInfo();// 考试信息
    courseRows.clear(); // 最近学习课程
    examPaperRows.clear(); //

    request_get_json('homePage/info').then((val){
      var data = json.decode(val.toString());
      int status = data['status'];
      // 如果服务端相应代码为10，则需要登录
      if(status==10){
        setState(() {
          Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage()));
        });
      }else {
        homePageInfo = HomePageInfo.fromJson(data['data']);
        setState(() {
          swiperDataList = homePageInfo.slides; // 轮播图
          examInfo = homePageInfo.examInfo; // 考试信息
          courseRows = homePageInfo.courseRows; // 最近学习课程
          examPaperRows = homePageInfo.examPaperRows; // 最近学习试卷
        });
      }
    });
  }
  // 空数据显示
  Widget emptyShowInfo(context){
    return Image.asset(KImage.homePage,
      fit: BoxFit.fitWidth,
      width: ScreenUtil().width,
    );
  }
}

// 首页轮播组件编写
class SwiperDiy extends StatelessWidget{
  final List swiperDataList;
  SwiperDiy({Key key, this.swiperDataList}):super(key:key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(10),
      height: ScreenUtil().setHeight(240),
      width: ScreenUtil().setWidth(600),
      child: Swiper(
        itemBuilder: (BuildContext context, int index){
          var _image = swiperDataList[index];
          String imageUrl;
          if (_image == null) {
            imageUrl = '';
          } else {
            imageUrl = HomePageImageInfo.fromJson(_image).pictureUrl;
          }
          return InkWell(
            child: Image.network(imageUrl,
              fit: BoxFit.scaleDown,
            ),
            onTap: (){
            },
          );
        },
        itemCount: swiperDataList.length,
        pagination: new SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

// 首页考试信息组件
class ExamPromptInformation extends StatelessWidget {
  ExamInfo examInfo;
  ExamPromptInformation({Key key, this.examInfo}) :super(key: key);

  @override
  Widget build(BuildContext context) {
    String examTitle = examInfo.examTitle;
    int remainderDays = examInfo.remainderDays;
    String examExplain = examInfo.examExplain;
    String remainderDays_ = remainderDays == null ? '-': remainderDays.toString()  ;
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.all(2.0),
      height: ScreenUtil().setHeight(150),
      padding: EdgeInsets.all(3.0),
      decoration: new BoxDecoration( // 边框设置
        color: Colors.white,
        border: new Border.all(width: 1, color: Colors.white),
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        //设置四周边框
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Text(examTitle, style: TextStyle(
                  fontSize: 20
              ),
              ),
              Text(remainderDays_, style: TextStyle(
                fontSize: 30,
                color: Colors.red,
              ),
              ),
              Text('天', style: TextStyle(
                  fontSize: 20
              ),
              ),
            ],
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(left: 20,right: 20),
                  alignment: Alignment.center,
                  child: Text(examExplain, style: TextStyle(
                        fontSize: 17
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}


class LastStudy extends StatelessWidget {
  List courseRows;
  List examPaperRows;
  LastStudy({Key key, this.courseRows, this.examPaperRows}) :super(key: key);

  @override
  Widget build(BuildContext context) {
    double totalHeight = (courseRows.length >= examPaperRows.length ? courseRows.length:examPaperRows.length)*150.0;
    
    return Container(
      height: ScreenUtil().setHeight(totalHeight),
      alignment: Alignment.center,
      margin: EdgeInsets.all(2.0),
      padding: EdgeInsets.all(3.0),
      child: Column(
        children: <Widget>[
          Container(
            color: KColor.primaryColor,
            alignment: Alignment.centerLeft,
            height: ScreenUtil().setHeight(80),
            child: Row(
              children: <Widget>[
                Container(
                  child: Icon(Icons.book),
                  margin: EdgeInsets.only(left: 10, right: 10),
                ),
                Expanded(
                  child: Text('最近学习',
                    style: KFont.courseTitleStyle,
                  ) ,
                ),
              ],
            ),
          ),
          HomePageCourseColumn(courseRows: courseRows,),
          HomePageExamPaperColumn(examPaperRows: examPaperRows,)
        ],
      )
    );
  }
}

// 最近学习组件
class LatelyOperate extends StatefulWidget{
  List courseRows;
  List examPaperRows;
  LatelyOperate({Key key,this.courseRows, this.examPaperRows,}):super(key: key);
  @override
  State<StatefulWidget> createState() => new _LatelyOperateState(courseRows: courseRows, examPaperRows: examPaperRows,);
}
// 最近学习组件
class _LatelyOperateState extends State<LatelyOperate> with SingleTickerProviderStateMixin{
  List courseRows;
  List examPaperRows;
  _LatelyOperateState({this.courseRows, this.examPaperRows});
  TabController _tabController ;

  @override
  void initState() {
    super.initState();
    // 初始化 Tab 导航视图监听
    this._tabController = new TabController(vsync:this, length: 2);
//    _tabController.addListener((){
//    });
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(1.0),
      decoration: new BoxDecoration( // 边框设置
        color: Colors.white,
        border: new Border.all(width: 1, color: Colors.white),
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(10.0)),
        //设置四周边框
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            color: KColor.primaryColor,
            alignment: Alignment.centerLeft,
            height: ScreenUtil().setHeight(80),
            child: Row(
              children: <Widget>[
                Container(
                  child: Icon(Icons.book),
                  margin: EdgeInsets.only(left: 10, right: 10),
                ),

                Expanded(
                  child: Text('最近学习',
                    style: KFont.courseTitleStyle,
                  ) ,
                ),
              ],
            ),
          ),
          Container(
            height: ScreenUtil().height,
            color: Colors.white,
            child: Scaffold(
              appBar: AppBar(
                backgroundColor: Colors.white,
                title: TabBar(
                  indicatorSize: TabBarIndicatorSize.tab,
                  labelColor: Colors.blueAccent,
                  unselectedLabelColor: Colors.black,
                  indicatorColor: Colors.white,
                  tabs: <Widget>[
                    _getTab("课程"),
                    _getTab("试卷"),
                  ],
                  controller: this._tabController,
                ),
              ),
              body: TabBarView(
                controller: this._tabController,
                children: <Widget>[
                  new Container(
                    child: HomePageCourseColumn(courseRows:courseRows),
                  ),
                  new Container(
                    child: HomePageExamPaperColumn(examPaperRows: examPaperRows),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Tab _getTab(titleName){
    return new Tab(
      child: Row(
        children: <Widget>[
          Icon(Icons.book, size: 20,),
          Text(titleName,
            textAlign: TextAlign.left,
            style: TextStyle(
              fontSize: 20,
            ),
          ),
        ],
      ),
    );
  }
  @override
  void dispose() {
//    this._tabController.dispose();
    super.dispose();
  }
}

// 首页课程列表
class HomePageCourseColumn extends StatefulWidget{
  List courseRows;
  HomePageCourseColumn({Key key,this.courseRows}):super(key: key);

  @override
  State<StatefulWidget> createState() => new _HomePageCourseColumnState(courseRows:this.courseRows);
}
// 首页课程列表
class _HomePageCourseColumnState extends State<HomePageCourseColumn>{
  List courseRows;
  _HomePageCourseColumnState({this.courseRows});

  ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: _buildBody(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    // 1 数据为空时, 显示空视图
    if (courseRows== null || courseRows.length == 0) {
      return Center(
        child: Text('那家伙很懒，什么都没学 ...',
          style: TextStyle(
              fontSize: 22,
              color: Colors.black38
          ),
        ),
      );
    }
    // 2 构建视图列表
    ListView listView = ListView.builder(
      itemBuilder: this.buildTitleContent,
      itemCount: this.courseRows.length,
      controller: _controller,
    );
    return listView;
  }

  Widget buildTitleContent(context, index) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 2.0),
      margin: const EdgeInsets.only(bottom: 2.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          new BoxShadow(
            color: const Color(0xFFd0d0d0),
            blurRadius: 1.0,
            spreadRadius: 2.0,
            offset: Offset(3.0, 2.0),
          ),
        ],
      ),
      child: _listTitle(index),
    );
  }

  Widget _listTitle(index){
    var courseJson = this.courseRows[index];
    Course course = Course.fromJson(courseJson);
    return  ListTile(
      leading: Image.network(course.logoUrl,
        height: 150,
      ),
      title: Text(
        course.name,
        overflow: TextOverflow.ellipsis,
        style:  KFont.courseTitleStyle,
      ),
      subtitle:Text(course.subTitle,
        style: KFont.courseSubTitleStyle,
      ),
      trailing:
      Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
      onTap: () {
        Navigator.push(context, MaterialPageRoute(
            builder:(context){
              return new CourseQuestionPage(course:course, isAddStudyFlag: true,);
            }
        ));
      },
    );
  }
}

// 试卷视图组件
class HomePageExamPaperColumn extends StatefulWidget{
  final List examPaperRows; // 课程信息
  HomePageExamPaperColumn({Key key,@required this.examPaperRows}):super(key:key);

  @override
  State<StatefulWidget> createState() => new _HomePageExamPaperColumnState(examPaperRows: this.examPaperRows, key:this.key);
}

class _HomePageExamPaperColumnState extends State<HomePageExamPaperColumn> {
  List examPaperRows;
  Key key;
  _HomePageExamPaperColumnState({this.examPaperRows, this.key});

  ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
          child: _buildBody(),
        ),
    );
  }
  // 构建Body
  Widget _buildBody() {
      if(examPaperRows== null || examPaperRows.length == 0){
        return Center(
          child: Text('那家伙很懒，什么都没学 ...',
            style: TextStyle(
                fontSize: 22,
                color: Colors.black38
            ),
          ),
        );
      }
      // 2 构建视图列表
      ListView listView = ListView.builder(
        itemBuilder: _buildListView,
        itemCount: examPaperRows.length,
        controller: _controller,
      );
      return listView;
  }
  // 构建单条数据信息
  Widget _buildListView(context, index){
    ExamPaper examPaper = ExamPaper.fromJson(examPaperRows[index]);
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 2.0),
      margin: const EdgeInsets.only(bottom: 2.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          new BoxShadow(
            color: const Color(0xFFd0d0d0),
            blurRadius: 1.0,
            spreadRadius: 2.0,
            offset: Offset(3.0, 2.0),
          ),
        ],
      ),
      child: ListTile(
//        selected: true,
        leading: Image.asset(KImage.examPaper, height: 100),
        title: Text((examPaper.courseName + '--' + examPaper.smallName),
          overflow: TextOverflow.ellipsis,
          style:  KFont.courseTitleStyle,
        ),
        subtitle:Text(examPaper.examPaperName,
          style: KFont.courseSubTitleStyle,
        ),
        trailing: Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 40.0),
        onTap: () {
          Navigator.push(context, MaterialPageRoute(
              builder:(context){
                return ExamPaperQuestionPage(course:Course(code: examPaper.courseCode), examPaper:examPaper, isAddStudyFlag: true,);
              }
          ));
        },
      ),
    );
  }
  @override
  void dispose() {
    super.dispose();
  }
}
